import { getPeerCarPage } from '../../api/peerCar/index'
import config from '../../config/index'
Page({
  data: {
    currentPage: 1,
    searchKey: '',
    peerCarList: [] as ListPeerCar[]
  },
  toAdd() {
    wx.navigateTo({
      url: '/pages/addPeer/addPeer'
    })
  },
  onShow() {
    this.setData({
      currentPage: 1,
      searchKey: ''
    })
    this.initList(this.data.currentPage, this.data.searchKey)
  },
  onReachBottom() {
    wx.showLoading({title: '加载中'})
    let that = this
    that.setData({
      currentPage: this.data.currentPage + 1
    })
    getPeerCarPage(this.data.currentPage, this.data.searchKey).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        let carRes = res.data.data as ListPeerCar[]
        let newList = [...this.data.peerCarList, ...carRes]
        that.setData({
          peerCarList: newList
        })
        wx.hideLoading()
      }
    })
  },
  async initList(page: number, brand: string) {
    const res = await getPeerCarPage(page, brand)
    if(res.statusCode === config.SUCCESS_CODE) {
      let carRes = res.data
      this.setData({
        peerCarList: carRes.data as ListPeerCar[]
      })
    } else {
      wx.showToast({
        title: '获取失败请重试',
        icon: 'error'
      })
    }
  },
  search() {
    this.initList(1, this.data.searchKey)
  },
  toDetail(e: any) {
    let id: string = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/peerCarDetail/peerCarDetail?id=${id}`
    })
  }
})